import React, { PureComponent } from "react";
import { requireNativeComponent, findNodeHandle, UIManager, Platform, View, StyleSheet } from "react-native";

const AMapView = requireNativeComponent("AMapView");
const AMapMarker = requireNativeComponent("AMapMarker");
const AMapPolyline = requireNativeComponent("AMapPolyline");

function callNativeFun(component, componentName, name, params) {
  const handle = findNodeHandle(component);
  if (handle) {
    const command = UIManager.getViewManagerConfig(componentName).Commands[name];
    UIManager.dispatchViewManagerCommand(handle, command, params);
  }
}

export class MapView extends PureComponent {
    setStatus(status, duration = 0) {
      callNativeFun(this, "AMapView", "setStatus", [status, duration]);
    }
    
    render() {
        return <AMapView {...this.props} />;
    }
}

export class Marker extends PureComponent {
    componentDidMount() {
      this._ismounted = true;
    }
    
    componentWillUnmount() {
      this._ismounted = false;  
    }

    componentDidUpdate() {
      if (this.icon && Platform.OS === "android") {
        setTimeout(() => this._ismounted && callNativeFun(this, "AMapMarker", "update"), 0);
      }
    }
  
    active() {
      callNativeFun(this, "AMapMarker", "active");
    }
  
    update() {
      callNativeFun(this, "AMapMarker", "update");
    }
  
    lockToScreen(x, y) {
      callNativeFun(this, "AMapMarker", "lockToScreen", [x, y]);
    }
  
    renderCustomMarker(icon) {
      if (icon) {
        this.icon = <View style={style.overlay}>{icon()}</View>;
        return this.icon;
      }
      return null;
    }
  
    render() {
      return (
        <AMapMarker {...this.props}>
          {this.renderCustomMarker(this.props.icon)}
        </AMapMarker>
      );
    }
  }

  export class Polyline extends PureComponent {
    render() {
      return <AMapPolyline {...this.props} />;
    }
  }

  const style = StyleSheet.create({
    overlay: {
      position: "absolute",
    },
  });
